<?php
declare (strict_types = 1);

namespace app\middleware;
use lizhili\Time;
use think\facade\Db;
class LizhiliIndexInit
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {

        if(request()->controller()!="Install"){
            //这里记录所有的访问数据
            list($start, $end) = Time::today();
            if($b=Db::name('statistics')->where('time','>=',$start)->where('time','<',$end)->find()){
                Db::name('statistics')->where('id',$b['id'])->inc('pv')->update();
                if(Db::name('statistics_show')->where('ip',$request->ip())->find()){
                    if(!Db::name('statistics_show')->where('time','>=',$start)->where('time','<',$end)->where('ip',$request->ip())->find()){
                        Db::name('statistics')->where('id',$b['id'])->inc('uv')->update();
                    }
                }else{
                    Db::name('statistics')->where('id',$b['id'])->inc('ip')->update();
                }
            }else{
                $id=Db::name('statistics')->insertGetId([
                    'time'=>time(),
                    'ip'=>0,
                    'pv'=>1,
                    'uv'=>1
                ]);
                if(!Db::name('statistics_show')->where('ip',$request->ip())->find()){
                    Db::name('statistics')->where('id',$id)->inc('ip')->update();
                }
            }
            $a=[
                'time'=>time(),
                'ip'=>$request->ip(),
                'url'=>$request->url(true),
                'data'=>json_encode(input('param.')),
                'method'=>$request->method(),
                'controller'=>$request->controller(),
                'module'=>'index',
                'action'=>$request->action(),
                'file'=>!$request->file() ? 0 : sizeof($request->file()),
            ];
            Db::name('statistics_show')->insert($a);
        }
        if(request()->controller()!=="Notify" and request()->controller()!=="Install"){ //这个是微信支付的回调，以后回调都写在这个控制器里面的了
            $system= Db::name('system')->column('value','enname');
            if($system["is_open"] != "开启"){
                if($system["redirect"]){
                    return redirect($system["redirect"], '',302);
                }
                return json(['非法访问'])->code(404);
                exit('网站关闭');
            }
        }
        return $next($request);
    }
}
